package ratelimit

import (
	"context"
	"errors"
	"gitee.com/chicken-c/go-learn/webook/internal/service/sms"
	"gitee.com/chicken-c/go-learn/webook/pkg/ratelimit"
)

var errLimited = errors.New("短信服务触发限流")

// 装饰器模式
type RateLimitSMSService struct {
	//被装饰的
	sms     sms.Service
	limiter ratelimit.Limiter
	key     string
}

func NewRateLimitSMSService(sms sms.Service, limiter ratelimit.Limiter) *RateLimitSMSService {
	return &RateLimitSMSService{
		sms:     sms,
		limiter: limiter,
		key:     "Alibaba-SMS",
	}
}

func (r *RateLimitSMSService) Send(ctx context.Context, tqlId string, args map[string]string, number string) error {
	limited, err := r.limiter.Limit(ctx, r.key)
	if err != nil {
		return err
	}
	if limited {
		//被限流了
		return errLimited
	}

	return r.sms.Send(ctx, tqlId, args, number)
}
